package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBeanCondition;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckItemService;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
	@Autowired
	JedisPool jedisPool;
	@Autowired
	SetmealDao setmealDao;
	@Autowired
	private FreeMarkerConfig freeMarkerConfigurer;
	@Value("${out_put_path}")
	private String outputpath ;
	@Override
	public void add(Setmeal setmeal, Integer[] checkgroupIds) {
		setmealDao.add(setmeal);
		this.setCheckGroupAndItem(setmeal.getId(),checkgroupIds);
		//将图片名称保存到Redis
		savePic2Redis(setmeal.getImg());
		List<Setmeal> setmealList = setmealDao.findAll();
		generateMobileSetmealListHtml(setmealList);
		Setmeal setmealById = setmealDao.findById(setmeal.getId());
		generateMobileSetmealDetailHtml(setmealById);
	}
	//将图片名称保存到Redis
	private void savePic2Redis(String pic){
		jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
	}
	//生成套餐列表静态页面
	public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("setmealList", setmealList);
		this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
	}
	//生成套餐详情静态页面（多个）
	public void generateMobileSetmealDetailHtml(Setmeal setmealById) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("setmeal", setmealById);
		this.generateHtml("mobile_setmeal_detail.ftl",
				"setmeal_detail_"+setmealById.getId()+".html",
				dataMap);
	}

	//通用方法
	public void generateHtml(String templateName,String htmlPageName,Map<String, Object> dataMap){
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Writer out = null;
		try {
			// 加载模版文件
			Template template = configuration.getTemplate(templateName);
			// 生成数据
			File docFile = new File(outputpath + "\\" + htmlPageName);
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
			// 输出文件
			template.process(dataMap, out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != out) {
					out.flush();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	@Override
	public PageResult findPage(QueryPageBeanCondition queryPageBeanCondition) {
		Integer currentPage = queryPageBeanCondition.getCurrentPage();
		Integer pageSize = queryPageBeanCondition.getPageSize();
		PageHelper.startPage(currentPage,pageSize);
		Page<CheckGroup> page =  setmealDao.selectByCondition(queryPageBeanCondition);
		long total = page.getTotal();
		List<CheckGroup> rows = page.getResult();
		return new PageResult(total,rows);
	}

	@Override
	public List<Setmeal> findSetmeal(String queryGroupName) {
//		try {
//			Integer group_id = setmealDao.findGSetmeal(queryGroupName);
//			Integer setmeal_id = setmealDao.findSetmealId(group_id);
//			return setmealDao.findSetmealIdAll(setmeal_id);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return new Result("查询失败");
		List<Setmeal> byGroupName = setmealDao.findByGroupName(queryGroupName);
		return byGroupName;
	}

	@Override
	public List<Setmeal> findAll() {
		return setmealDao.findAll();
	}

	@Override
	public Setmeal findById(int id) {
		return setmealDao.findById(id);
	}

	@Override
	public List<Map<String, Object>> findSetmealCount() {
		return setmealDao.findSetmealCount();
	}

	@Override
	public List<Map<String, Object>> findSetmealCountTwo() {
		return setmealDao.findSetmealCountTwo();
	}


	public void setCheckGroupAndItem(Integer setmeal_id, Integer[] checkgroupIds) {
		if(checkgroupIds!=null&&checkgroupIds.length>0){
			for (Integer checkgroupId : checkgroupIds) {
				Map<String,Integer> map = new HashMap<>();
				map.put("setmeal_id",setmeal_id);
				map.put("checkgroup_id",checkgroupId);
				setmealDao.setCheckGroupAndSetmeal(map);
			}
		}
	}
}
